const db = require("../db/index");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const { secretKey, expiresIn } = require("../config/index");
const uuid = require("node-uuid");

//注册
exports.regist = (req, res) => {
  const userInfo = req.body;
  const sql = "SELECT * FROM user WHERE account = ?";
  db.query(sql, userInfo.account, (err, results) => {
    //执行SQL失败
    if (err) return res.send({ status: 0, message: err.message });
    if (results.length > 0) {
      return res.send({ status: 500, message: "用户已被注册,请更换用户名！" });
    }
    //密码hash加密
    userInfo.password = bcrypt.hashSync(userInfo.password, 10);
    //用户UUID
    userInfo.userId = uuid.v1();
    userInfo.name = userInfo.account;
    userInfo.userImage = "";
    userInfo.lat = "";
    userInfo.lng = "";
    const sql = "INSERT INTO user SET ?";
    db.query(sql, userInfo, (err, results) => {
      //执行SQL失败
      if (err) return res.send({ status: 0, message: err.message });
      if (results.affectedRows !== 1) {
        return res.send({
          status: 500,
          message: "注册用户失败，请联系管理员！",
        });
      }
      res.send({ status: 200, message: "用户注册成功!" });
    });
  });
};

//登录
exports.login = (req, res) => {
  const userInfo = req.body;
  const sql = "SELECT * FROM nn_user WHERE account = ?";
  db.query(sql, userInfo.account, (err, results) => {
    if (err) return res.send({ status: 0, message: err.message });
    if (results.length !== 1) {
      return res.send({
        status: 500,
        message: "登陆失败，请检查用户名和密码！",
      });
    }
    // 判断密码是否正确
    const flag = bcrypt.compareSync(userInfo.password, results[0].password);
    if (!flag)
      return res.send({ status: 403, message: "登录失败，密码错误！" });
    //jwt加密userId 生成token
    const token = jwt.sign({ userId: results[0].uid }, secretKey, {
      expiresIn: expiresIn,
    });
    res.send({
      status: 200,
      message: "登录成功",
      token: "Bearer " + token,
      data: results,
    });
  });
};

//移除账号
exports.removeAccount = (req, res) => {
  console.log(req.headers.authorization.slice(7), "req");
  const token = req.headers.authorization.slice(7);
  const userInfo = req.body;
  if (token == null) {
    res.send({
      status: 500,
      message: "token错误",
    });
    return;
  }
  jwt.verify(token, secretKey, (err, data) => {
    if (err) {
      res.send({
        status: 500,
        message: "token解析失败",
      });
      return;
    }
    console.log(data, "jwt解析");
    const sql = "DELETE FROM nn_user WHERE uid = ?";
    //如果有多个参数，query的第二个入参是数组
    console.log(userInfo, "userInfo");
    db.query(sql, data.userId, (err, results) => {
      if (err) {
        console.log(err, "err");
        return res.send({ status: 500, message: "未找到用户" });
      }
      console.log(results, "sql results");
      res.send({
        status: 200,
        message: "用户已注销",
      });
    });
  });
};

//用户第一次登录
exports.firstRegist = (req, res) => {
  const userInfo = req.body;
  const sql = "INSERT INTO hh_user SET ?";
  db.query(sql, userInfo, (err, results) => {
    //执行SQL失败
    //jwt加密userId 生成token
    console.log(err, results);
    const token = jwt.sign({ userId: userInfo.uid }, secretKey, {
      expiresIn: expiresIn,
    });
    if (err) return res.send({ status: 0, message: err.message });
    if (results.affectedRows !== 1) {
      return res.send({ status: 500, message: "注册用户失败！" });
    }
    res.send({
      status: 200,
      message: "用户注册成功!",
      token: "Bearer " + token,
    });
  });
};

//绑定用户账号
exports.bindAccount = (req, res) => {
  console.log(req.headers.authorization.slice(7), "req");
  const token = req.headers.authorization.slice(7);
  const userInfo = req.body;
  if (token == null) {
    res.send({
      status: 500,
      message: "token错误",
    });
    return;
  }
  const { account, password } = userInfo;

  jwt.verify(token, secretKey, (err, data) => {
    if (err) {
      res.send({
        status: 500,
        message: "token解析失败",
      });
      return;
    }
    console.log(data, "jwt解析");
    const userSql = "SELECT * FROM nn_user WHERE account = ?";
    db.query(userSql, userInfo.account, (err, results) => {
      //执行SQL失败
      if (err) return res.send({ status: 0, message: err.message });
      if (results.length > 0) {
        return res.send({
          status: 500,
          message: "该账号已被其它用户绑定，请更换",
        });
      }
      const sql = "UPDATE nn_user SET account = ?,password = ? WHERE uid = ?";
      //如果有多个参数，query的第二个入参是数组
      console.log(userInfo, "userInfo");
      db.query(
        sql,
        [account, bcrypt.hashSync(userInfo.password, 10), data.userId],
        (err, results) => {
          if (err) {
            console.log(err, "err");
            return res.send({ status: 500, message: "未找到用户" });
          }
          console.log(results, "sql results");
          res.send({
            status: 200,
            message: "绑定成功",
          });
        }
      );
    });
  });
};

//获取活跃用户
exports.getActiveUsers = (req, res) => {
  console.log(req.headers.authorization.slice(7), "req");
  const token = req.headers.authorization.slice(7);
  const userInfo = req.body;
  if (token == null) {
    res.send({
      status: 500,
      message: "token错误",
    });
    return;
  }
  jwt.verify(token, secretKey, (err, data) => {
    if (err) {
      res.send({
        status: 500,
        message: "token解析失败",
      });
      return;
    }
    console.log(data, "jwt解析");
    const userSql = "SELECT * FROM nn_user ORDER BY updateTime DESC LIMIT 50";
    db.query(userSql, userInfo.count, (err, results) => {
      //执行SQL失败
      if (err) return res.send({ status: 0, message: err.message });
      // if (results.length == 0) {
      return res.send({
        status: 200,
        data: results,
        message: "获取活跃用户信息成功",
      });
      // }
    });
  });
};

// 获取其他用户最新信息
exports.getActiveUsersInfo = (req, res) => {
  console.log(req.headers.authorization.slice(7), "req");
  const token = req.headers.authorization.slice(7);
  const userInfo = req.body;
  if (token == null) {
    res.send({
      status: 500,
      message: "token错误",
    });
    return;
  }
  jwt.verify(token, secretKey, (err, data) => {
    if (err) {
      res.send({
        status: 500,
        message: "token解析失败",
      });
      return;
    }
    console.log(data, "jwt解析");
    const userSql =
      "SELECT * FROM nn_history WHERE uid = ? ORDER BY createTime DESC LIMIT 10";
    db.query(userSql, userInfo.uid, (err, results) => {
      //执行SQL失败
      if (err) return res.send({ status: 0, message: err.message });
      // if (results.length == 0) {
      return res.send({
        status: 200,
        data: results.length == 0 ? [] : [results[0]],
        message: "获取活跃用户信息成功",
      });
      // }
    });
  });
};

//绑定用户是VIP信息
exports.bindUserVIP = (req, res) => {
  console.log(req.headers.authorization.slice(7), "req");
  const token = req.headers.authorization.slice(7);
  const userInfo = req.body;
  if (token == null) {
    res.send({
      status: 500,
      message: "token错误",
    });
    return;
  }
  jwt.verify(token, secretKey, (err, data) => {
    if (err) {
      res.send({
        status: 500,
        message: "token解析失败",
      });
      return;
    }
    console.log(data, userInfo, "jwt解析");
    const sql = "UPDATE nn_user SET vip = ? WHERE uid = ?";
    //如果有多个参数，query的第二个入参是数组
    console.log(userInfo, "userInfo");
    db.query(sql, [userInfo.isVip, data.userId], (err, results) => {
      if (err) {
        console.log(err, "err");
        return res.send({ status: 500, message: "未找到用户" });
      }
      console.log(results, "sql results");
      res.send({
        status: 200,
        message: "VIP用户绑定成功",
      });
    });
  });
};
